package com.xinziruo.crawl.infrastruture.messaging;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

import com.xinziruo.crawl.application.CrawlEvents;
import com.xinziruo.crawl.domain.crawl.api.CrawlEvent;
import com.xinziruo.crawl.domain.crawl.api.CrawlEventFilterChain;
import com.xinziruo.crawl.domain.crawl.api.CrawlEventHandler;

/**
 * 
 * @author loudyn
 * 
 */
public class QueueingCrawlEvents implements CrawlEvents, InitializingBean {

	private Logger logger = LoggerFactory.getLogger(QueueingCrawlEvents.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.youboy.crawl.application.CrawlEvents#crawlEventWasCreated(com.youboy
	 * .crawl.domain.crawl.api.CrawlEvent)
	 */
	@Override
	public void crawlEventWasCreated(final CrawlEvent crawlEvent, final CrawlEventFilterChain filterChain) {

		executor.submit(new Runnable() {

			@Override
			public void run() {

				try {

					filterChain.filter(crawlEvent);
					CrawlEventHandler handler = filterChain.getHandler();
					handler.handle(crawlEvent);
				} catch (Exception e) {
					logger.error("error occur on handle crawlEvent!", e);
				}
			}
		});
	}

	private int poolSize = 20;
	private ExecutorService executor;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
	 */
	@Override
	public final void afterPropertiesSet() throws Exception {
		initializeThreadPool();
	}

	protected void initializeThreadPool() {
		if (poolSize <= 0) {
			throw new IllegalArgumentException("poolSize must gt 0!");
		}

		executor = Executors.newFixedThreadPool(this.poolSize);
	}

	public void setPoolSize(int poolSize) {
		this.poolSize = poolSize;
	}
}
